package cn.icyzx.configure;

import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import cn.icyzx.util.GetServerUtil;

import javax.sql.DataSource;

/**
 * 包含了mybatis 的唯一DataSource , SqlSessionFactory 以及开启了事务管理
 *
 * @Author zk
 * @Date 2017/2/11.
 * @Email 2117251154@qq.com
 */
@EnableTransactionManagement
@Configuration
@MapperScan("cn/icyzx/dao")
public class MybatisConfigure {

    private static Logger logger = Logger.getLogger(MybatisConfigure.class);

    @Bean
    public DataSource dataSource() {
        final String url = GetServerUtil.getJdbcUrl();
        final String username = GetServerUtil.getJdbcUsername();
        final String password = GetServerUtil.getJdbcPassword();
        final String driver = GetServerUtil.getJdbcDriver();

        DataSource source = new PooledDataSource(driver, url, username, password);

        logger.info("initialize dataSource");
        return source;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);

        InputStreamResource inputStreamResource =
                new InputStreamResource(MybatisConfigure.class.getClassLoader().getResourceAsStream("mapper.xml"));
        Resource[] resouce = {inputStreamResource};
        sessionFactory.setMapperLocations(resouce);
        logger.info("initialize mybatis SqlSessionFactory");
        return sessionFactory.getObject();
    }

    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager(DataSource dataSource) {
        logger.info("initialize TransactionManager");
        return new DataSourceTransactionManager(dataSource);
    }

}
